package com.tiyende.kash.loop.ui.activity

import android.net.Uri
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.tiyende.kash.loop.TiyendeApp
import com.tiyende.kash.loop.common.CommonActivity
import com.tiyende.kash.loop.databinding.TiyendeActivityCameraSelfieBinding
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.contract.IViewContract
import com.tiyende.kash.loop.ui.presenter.TiyendeImageUploadPresenter
import com.tiyende.kash.loop.utils.TiyendeDensityUtil
import com.tiyende.kash.loop.utils.TiyendeImageUtil
import com.tiyende.kash.loop.utils.TiyendeTitleBarUtil
import com.tiyende.kash.loop.utils.imgcovert.ImageConvert
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/22 17:12
 * @Annotation：自拍照
 */
class TiyendeCameraSelfieActivity: CommonActivity(), IViewContract.ITiyendeImageUploadView {
    private var _binding: TiyendeActivityCameraSelfieBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "camera selfie binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var upLoadPresenter: TiyendeImageUploadPresenter? = null

    private var cameraExecutor: ExecutorService? = null
    private var imageCapture: ImageCapture? = null
    private var imgUri: Uri? = null
    private var imgUsePath = ""


    override fun getTiyendeRootView(): View {
        _binding = TiyendeActivityCameraSelfieBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        TiyendeTitleBarUtil.setStatusBarLightMode(this, false)
        _binding?.selfieTitleLayout?.setPadding(0, TiyendeTitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        initPreviewScale()
        startCameraSelfie()
    }

    override fun initTiyendeListener() {
        _binding?.selfieImgBack?.setOnClickListener{
            finish()
        }
        _binding?.selfieImgCustomer?.setOnClickListener {
            val eventTitle = takeCameraPageName()
            showCustomerDialog(eventTitle)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,eventTitle)
        }
        //切换语言
        _binding?.selfieImgLanguage?.setOnClickListener {
            val eventTitle = takeCameraPageName()
            showTiyendeSwitchLanguageDialog(eventTitle, onConfirmCallback = {

            })
        }
        //拍照
        _binding?.imgCameraTake?.setOnClickListener{
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CAMERA_TAKE_PHOTO,takeCameraPageName())
            takeCameraSelfieFilePhoto()
        }

        //重拍
        _binding?.cameraRemakeLayout?.setOnClickListener{
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CAMERA_REMAKE_PHOTO,takeCameraPageName())
            showCameraFaceTakeView()
        }

        //使用
        _binding?.cameraUseLayout?.setOnClickListener{
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CAMERA_USE_PHOTO, takeCameraPageName())
            showTiyendeLoading()
            // 图片处理
            ImageConvert.covert(context = this@TiyendeCameraSelfieActivity, uri = imgUri) { localPath, bitmap ->
                if (localPath != null){
                    TiyendeLogger.e("imageConvert success>>>>>>>$localPath")

                    if (upLoadPresenter == null){
                        upLoadPresenter = TiyendeImageUploadPresenter(this)
                    }
                    if (localPath.isNotEmpty()){
                        showTiyendeLoading()
                        upLoadPresenter?.submitUploadImageAction(localPath)
                    }
                }
            }
        }
    }

    override fun loadTiyendeData() {
    }

    /**
     * 打开相机预览
     */
    private fun startCameraSelfie() {
        showCameraFaceTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_4_3)
                .build()
                .also {
                    it.setSurfaceProvider(_binding?.selfieCameraView?.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 设置相机画面和拍照预览View的宽高和位置
     */
    private fun initPreviewScale(){
        // 确保 PreviewView 的布局参数设置为 4:3
        _binding?.selfieCameraView?.post {
            val width = TiyendeApp.app.getPhoneWidth() - TiyendeDensityUtil.dp2px(100f)
            val layoutParams = _binding?.selfieCameraView?.layoutParams
            layoutParams?.width = width
            layoutParams?.height = width
            _binding?.selfieCameraView?.layoutParams = layoutParams

            _binding?.selfieCameraView?.y = ((TiyendeApp.app.getPhoneHeight() - width) / 3).toFloat()
        }

        _binding?.selfiePreview?.post {
            val width = TiyendeApp.app.getPhoneWidth() - TiyendeDensityUtil.dp2px(100f)
            val layoutParams = _binding?.selfiePreview?.layoutParams
            layoutParams?.width = width
            layoutParams?.height = width
            _binding?.selfiePreview?.layoutParams = layoutParams

            _binding?.selfiePreview?.y = ((TiyendeApp.app.getPhoneHeight() - width) / 3).toFloat()
        }
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeCameraSelfieFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = TiyendeApp.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata().apply {
                // 当为前置摄像头时镜像；前置摄像头预览时默认就是镜像
                isReversedHorizontal = true
            }
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    imgUri = outputFileResults.savedUri
                    imgUri?.path?.let { path ->
                        TiyendeLogger.e("take photo complete>>>>>>>${path}")
                        imgUsePath = path
                        showCameraFaceCompleteView()
                    }
                }
                override fun onError(exception: ImageCaptureException) {
                    TiyendeLogger.e("take photo failed >>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showCameraFaceTakeView(){
        _binding?.let { binding ->
            binding.selfiePreview.visibility = View.GONE
            binding.imgCameraTake.visibility = View.VISIBLE
            binding.cameraUseLayout.visibility = View.GONE
            binding.cameraRemakeLayout.visibility = View.GONE
        }
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCameraFaceCompleteView(){
        _binding?.let { binding ->
            TiyendeImageUtil.instance?.loadImageUrl(this@TiyendeCameraSelfieActivity,binding.selfiePreview,imgUsePath,0)
            binding.selfiePreview.visibility = View.VISIBLE
            binding.imgCameraTake.visibility = View.INVISIBLE
            binding.cameraUseLayout.visibility = View.VISIBLE
            binding.cameraRemakeLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 图片上传完成
     */
    private fun showTiyendeUploadImageSuccess(imgPath: String, imgUrl: String) {
        val intent = intent
        intent.putExtra("imgLocalPath",imgUsePath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    /**
     * 获取页面名称
     */
    private fun takeCameraPageName(): String{
        var eventRemark = ""
        intent.extras?.let {
            eventRemark = it.getString("pageName","Selfie Step")
        }
        return eventRemark
    }

    /**
     * 图片上传完成
     */
    override fun showTiyendeImageUploadSuccess(imgPath: String, imgUrl: String) {
        showTiyendeUploadImageSuccess(imgPath,imgUrl)
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_SELFIE_CAMERA_START,takeCameraPageName())
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_SELFIE_CAMERA_END,takeCameraPageName())
        cameraExecutor?.shutdown()
    }
}